from PyQt4.QtGui import QPushButton, QLabel, QLineEdit, QGridLayout, QComboBox, QDialogButtonBox, QPlainTextEdit, QHBoxLayout, QSpacerItem, QSizePolicy, QWidget
from phonik.plugin import Plugin
from PyQt4.QtGui import QFont
from PyQt4.QtGui import QDialog
from PyQt4 import QtGui
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtCore import QSize
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QString
from PyQt4.QtGui import QFileDialog, QDesktopServices
import encodings
import os
import subprocess


class TagConverter(Plugin):
    def load(self):

    # last visited path - used for file monitoring
        self.lastPath = ''

        # set plugin name
        self.setName('TagConverter')
        self.dialog = ConvertDialog(self.getMainWindow())
        self.createMenu()



    def createMenu(self):
        self.actionConvert = QtGui.QAction(self.getMainWindow())
        self.actionConvert.setText(self.tr('Convert ID3 tags to UTF8'))
        self.getMainWindow().menuExtras.addAction(self.actionConvert)
        self.actionConvert.triggered.connect(self.dialog.show)


class ConvertDialog(QDialog):
    def __init__(self, parent):
        
        QDialog.__init__(self, parent)
        self.setFixedSize(550, 330)
        self.setWindowTitle(self.tr("Dialog"))
        
        verticalLayout = QVBoxLayout(self)
        mainLabel = QLabel(self)
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        mainLabel.setFont(font)
        mainLabel.setText(self.tr("Convert ID3 tags from legacy encoding to Unicode"))
        verticalLayout.addWidget(mainLabel)

        gridLayout = QGridLayout()
        label1 = QLabel(self)
        label1.setText(self.tr("Select a folder: "))
        gridLayout.addWidget(label1, 0, 0, 1, 1)

        self.lineEdit = QLineEdit(self)
        gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        
        pushButton = QPushButton(self)
        pushButton.setText('...')
        pushButton.setMaximumSize(QSize(33, 16777215))
        pushButton.clicked.connect(self.selectDir)
        gridLayout.addWidget(pushButton, 0, 2, 1, 1)

        label2 = QLabel(self)
        label2.setText(self.tr("Original encoding: "))
        gridLayout.addWidget(label2, 1, 0, 1, 1)

        self.comboBox = QComboBox(self)
        self.fill(self.comboBox)
        gridLayout.addWidget(self.comboBox, 1, 1, 1, 2)

        verticalLayout.addLayout(gridLayout)

        self.plainTextEdit = QPlainTextEdit(self)
        self.plainTextEdit.setReadOnly(True)
        font = QFont()
        font.setPixelSize(10)
        self.plainTextEdit.setFont(font)
        verticalLayout.addWidget(self.plainTextEdit)

        widget = QWidget(self)
        horizontalLayout = QHBoxLayout(widget)
        horizontalLayout.setSpacing(0)
        horizontalLayout.setContentsMargins(0, 0, 0, 0)
        horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        horizontalLayout.addItem(horizontalSpacer)

        convertButton = QPushButton(widget)
        convertButton.setMaximumSize(QSize(85, 16777215))
        convertButton.setText(self.tr("Convert"))
        convertButton.clicked.connect(self.accept)

        horizontalLayout.addWidget(convertButton)

        closeButton = QPushButton(widget)
        closeButton.setObjectName(QString.fromUtf8("closeButton"))
        closeButton.setText(self.tr("Close"))
        closeButton.setMaximumSize(QSize(85, 16777215))
        closeButton.clicked.connect(self.reject)
        horizontalLayout.addWidget(closeButton)
        verticalLayout.addWidget(widget)

    def show(self):
        self.exec_()


    def cmd_output(self, args, **kwds):
          kwds.setdefault("stdout", subprocess.PIPE)
          kwds.setdefault("stderr", subprocess.STDOUT)
          p = subprocess.Popen(args, **kwds)
          return p.communicate()[0]

    def accept(self):
        self.plainTextEdit.clear()

        dir = self.lineEdit.text()
        encoding = str(self.comboBox.currentText())
        if dir:
            dir = unicode(dir.toUtf8(),'utf-8')
            for root, dirs, files in os.walk(dir):
                for file in files:
                    if file.lower().endswith('.mp3'):
                        filePath = os.path.join(root, file)
                        command = 'mid3iconv --remove-v1 -e ' + encoding + ' "' + filePath + '"'
                        out = os.popen4(command)
                        self.plainTextEdit.insertPlainText(QString.fromUtf8(out[1].read()))


    def reject(self):
        self.done(-1)


    def selectDir(self):
        dir = QFileDialog.getExistingDirectory(self, self.tr('Select a folder'),
              QDesktopServices.storageLocation(QDesktopServices.MusicLocation),QFileDialog.ShowDirsOnly)

        if dir:
            self.lineEdit.setText(dir)


    def fill(self, comboBox):

        for key in set(sorted(encodings.aliases.aliases.values())):
            comboBox.addItem(key)

        # set default encoding
        num = comboBox.findText ('cp1251')
        if num:
            comboBox.setCurrentIndex(num)